package com.iseastar.dianxiaosan.home.update;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.view.View.OnClickListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import droid.frame.activity.ActivityMgr;
import droid.frame.ui.dialog.AppDialog;

/**
 * 店小三版本升级，挪用裹儿
 *
 * @author HuXinDan<br>
 * 2016-12-5下午3:33:28
 */
public class Update {
    private final String FILE_NAME = "temp.apk";

    private Context mContext;

    private Handler mHandler = new Handler();

    public Update(Context context) {
        mContext = context;
    }

    private ProgressDialog pBar;

    public void doNewVersionUpdate(final String url, String description, int isMustUpdate) {
        final AppDialog dialog = new AppDialog((Activity) mContext, false);
        dialog.setTitle("检测到新版本，是否更新?");
        Spanned spanned = Html.fromHtml(description);
        dialog.setContent(spanned.toString());
        dialog.setConfirmClickListener("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pBar = new ProgressDialog(mContext);
                pBar.setTitle("请稍候……");
                pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pBar.setCancelable(false);
                downFile(url);
            }
        });
        if (isMustUpdate == 2) {
            dialog.setCancelClickListener("退出", new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    ActivityMgr.finishAll();
                }
            });
            dialog.setCancelable(false);
        } else {
            dialog.setCancelClickListener("下次再说", null);
            dialog.setCancelable(true);
        }

        dialog.show();
    }

    private void downFile(final String url) {
        pBar.show();
        new Thread() {
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL urlPath = new URL(url);
                    connection = (HttpURLConnection) urlPath.openConnection();
                    connection.connect();
                    double length = connection.getContentLength();
                    InputStream is = connection.getInputStream();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File file = new File(Environment.getExternalStorageDirectory(), FILE_NAME);
                        fileOutputStream = new FileOutputStream(file);
                        byte[] buf = new byte[1024];
                        int ch = -1;
                        double count = 0;
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);
                            count += ch;
                            int i = (int) (count / length * 100);
                            pBar.setProgress(i);
                        }
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                    down();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }.start();
    }

    private void down() {
        mHandler.post(new Runnable() {
            public void run() {
                pBar.cancel();
                update();
            }
        });
    }

    private void update() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//
        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), FILE_NAME)),
                "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }

}
